package com.sch.www.auth.oauth;

import com.sch.www.entity.SysMenu;
import com.sch.www.entity.SysRole;
import com.sch.www.entity.SysUser;
import com.sch.www.feign.UserApi;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.HashSet;


public class JdbcUserDetailsService implements UserDetailsService {


    UserApi userApi;

    public JdbcUserDetailsService(UserApi userApi) {
        this.userApi = userApi;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = userApi.findUserByUsername(username);
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        Collection<SimpleGrantedAuthority> simpleGrantedAuthorityCollection = new HashSet<>();
        for (SysRole role : sysUser.getRoles()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        for (SysMenu menu:sysUser.getMenus()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(menu.getPermission()));
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(sysUser.getUsername(), sysUser.getPassword(), simpleGrantedAuthorityCollection);

        return userDetails;
    }
}
